package gweb

import (
	"net"
	"log"
	"net/http"
	"io"
	"regexp"
	"fmt"
)

type Config struct {
	Addr  string
	Proto string
}

type server struct {
	Routes []route //路由
	c      *Config
	Logger *log.Logger
}

var defaultConfig = &Config{Addr:"", Proto:"9090"}
//启动
func (s *server)Run() error {
	var addr string = ""
	if s.c.Addr != "" {
		addr += s.c.Addr
	}
	if s.c.Proto != "" {
		addr += ":" + s.c.Proto
	}
	fmt.Println("******欢迎使用 Gweb ******* 正在监听：" + addr)
	l, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatal(err)
	}

	//调用这个函数可以启动server
	//当一个请求进来的时候 会调用 server#ServeHTTP
	return http.Serve(l, s)
}

func (s *server)ServeHTTP(w http.ResponseWriter, q *http.Request) {
	qUrl := q.URL.Path
	ctx := &Context{W:w, R:q, Params:map[string]string{}}
	q.ParseForm()
	if len(q.Form) > 0 {
		for k, v := range q.Form {
			ctx.Params[k] = v[0]
		}
	}

	//设置服务器标示名称
	ctx.SetHeader("Server", "tudo server", true)
	s.Logger.Println(qUrl)
	for _, v := range s.Routes {
		if v.path == qUrl&&v.methd == q.Method {
			v.handle.Hello(ctx)
			return
		}
	}

	s.NotFound(ctx)

}

func (s *server)NotFound(ctx *Context) {
	io.WriteString(ctx.W, "404 Page Not Found")
}

func (s *server)addRoute(path, meth string, h  MyHandle) {
	re, err := regexp.Compile(path)
	if err != nil {
		log.Fatal(err)
	}
	s.Routes = append(s.Routes, route{path:path, methd:meth, rrex:re, handle:h})
}